package lucene.server.web.config;


import lucene.server.common.model.Result;
import lucene.server.common.utils.JsonUtil;
import lucene.server.common.utils.SecretUtil;
import lucene.server.web.dao.SystemDao;
import lucene.server.web.dao.UserDao;
import lucene.server.web.model.LoginUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class AuthInterceptor  implements HandlerInterceptor {

    private static ConcurrentHashMap<String, LoginUser> userMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() throws SQLException {
        List<LoginUser> list = (List<LoginUser>) SystemDao.getAll("user",LoginUser.class);
        for (LoginUser user : list) {
            userMap.put(user.getUsername(),user);
        }
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        // 从 http 请求头中取出签名
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String requestUri = request.getRequestURI();

        if(requestUri.startsWith("/admin/")){
            String token = request.getHeader("token");
            if (token==null){
                response.getWriter().print(JsonUtil.toJson(Result.error("token不存在")));
                return false;
            } else if (checkAdmin(token)){
                return true;
            }else {
                response.getWriter().print(JsonUtil.toJson(Result.error("接口鉴权失败")));
                return false;
            }
        } else if(requestUri.startsWith("/client/") || requestUri.startsWith("/cdc/")){
            if (checkClient(request)){
                return true;
            }else {
                response.getWriter().print(JsonUtil.toJson(Result.error("接口鉴权失败")));
                return false;
            }
        }

        //验证成功
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
    private boolean checkAdmin(String token){

        if (userMap.containsKey(token)){
           return true;
        }

        LoginUser loginUser = UserDao.checkToken(token);

        if (loginUser==null){
            return false;
        }else{
            userMap.put(token,loginUser);
        }

        return true;
    }
    private boolean checkClient(HttpServletRequest request){

        String sign = request.getHeader("sign");
        String timestamp = request.getHeader("timestamp");
        String app = request.getHeader("app");
        LoginUser loginUser = getUser(app);

        String realSign = SecretUtil.generateMD5(app+loginUser.getPassword()+timestamp);
        if (!sign.equals(realSign)){
            return false;
        }else{
            return true;
        }
    }
    private LoginUser getUser(String userName){
        if (!userMap.containsKey(userName)){
            LoginUser loginUser = UserDao.getUser(userName);
            if (loginUser!=null){
                userMap.put(userName,loginUser);
            }
        }
        return userMap.get(userName);
    }
}
